import { RTColumn } from '../type/interfaces'

function safeRenderHeader(column: RTColumn) {
  return column.title ?? column.name
}

function safeGetValue(column: RTColumn, record: any, rowIndex: number) {
  return record[column.code]
}

function safeGetRowKey(primaryKey: string | ((record: any) => string), record: any, rowIndex: number): string {
  let key
  if (typeof primaryKey === 'string') {
    key = record[primaryKey]
  } else if (typeof primaryKey === 'function') {
    key = primaryKey(record)
  }
  if (key == null) {
    key = String(rowIndex)
  }
  return key
}


function safeRender(column: RTColumn, record: any, rowIndex: number) {
  const value = safeGetValue(column, record, rowIndex)
  if (column.render) {
    return column.render(value, record, rowIndex)
  }
  return value
}

export const transform = {
  safeRenderHeader,
  safeGetValue,
  safeGetRowKey,
  safeRender,
} as const
